const BaseController = require('./base_controller.js');
const RechargeManagementService = require('../service/recharge_management_service.js');

class RechargeManagementController extends BaseController {

  /**
   * 配置充值档位
   */
  async configRechargeLevels() {
    await this.isAdmin();

    // 数据校验
    let rules = {
      levels: 'required|array|name=充值档位',
    };

    let input = this.validateData(rules);

    try {
      const service = new RechargeManagementService();
      const result = await service.configRechargeLevels(input.levels);
      
      return this.success(result);
    } catch (error) {
      return this.fail(error.message);
    }
  }

  /**
   * 获取充值档位列表
   */
  async getRechargeLevels() {
    await this.isAdmin();

    try {
      const service = new RechargeManagementService();
      const result = await service.getRechargeLevels();
      
      return this.success(result);
    } catch (error) {
      return this.fail(error.message);
    }
  }

  /**
   * 管理员帮用户充值
   */
  async rechargeUser() {
    await this.isAdmin();

    // 数据校验
    let rules = {
      userId: 'required|string|name=用户ID',
      amount: 'required|int|min:1|name=充值金额',
      bonus: 'int|min:0|name=赠送金额',
      reason: 'required|string|max:200|name=充值原因',
    };

    let input = this.validateData(rules);

    try {
      const service = new RechargeManagementService();
      const result = await service.rechargeUser(input);
      
      return this.success(result);
    } catch (error) {
      return this.fail(error.message);
    }
  }

  /**
   * 扣除用户余额
   */
  async deductUserBalance() {
    await this.isAdmin();

    // 数据校验
    let rules = {
      userId: 'required|string|name=用户ID',
      amount: 'required|int|min:1|name=扣除金额',
      reason: 'required|string|max:200|name=扣除原因',
    };

    let input = this.validateData(rules);

    try {
      const service = new RechargeManagementService();
      const result = await service.deductUserBalance(input);
      
      return this.success(result);
    } catch (error) {
      return this.fail(error.message);
    }
  }

  /**
   * 获取用户充值记录
   */
  async getUserRechargeLogs() {
    await this.isAdmin();

    // 数据校验
    let rules = {
      page: 'int|min:1|default=1|name=页码',
      size: 'int|min:1|max:50|default=20|name=每页数量',
      userId: 'string|name=用户ID',
      dateRange: 'string|name=日期范围',
    };

    let input = this.validateData(rules);

    try {
      const service = new RechargeManagementService();
      const result = await service.getUserRechargeLogs(input);
      
      return this.success(result);
    } catch (error) {
      return this.fail(error.message);
    }
  }
}

module.exports = RechargeManagementController;
